<?php

namespace App\Console\Commands\Kms;

use App\Models\Kms\Album\AlbumResourceModel;
use App\Service\Kms\Album\AlbumResourceService;
use App\Service\OpenShop\Feishu\ConfigService;
use Illuminate\Console\Command;

class InitKmsAlbumResourceProvinceCode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'kms:InitAlbumResourceProvinceCode';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化运营app相册资源地址对应省市区code';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $getAmapDistrictJson = ConfigService::getAmapDistrictJson();
        AlbumResourceModel::query()
            ->where("provinceCode", 0)
            ->where("isDeleted", 0)
            ->chunkById(
                100, function ($item) use ($getAmapDistrictJson) {
                foreach ($item as $v) {
                    if ($v['id'] && $v['addressPrefix'] && $v['addressPrefix'] != '--') {
                        list($provinceCode, $cityCode, $districtCode) = AlbumResourceService::getProvinceCodeByAddress($v['addressPrefix'], $getAmapDistrictJson);
                        if ($provinceCode && $cityCode && $districtCode) {

                            AlbumResourceModel::query()->where("id", $v['id'])
                                ->update(
                                    [
                                        'provinceCode' => $provinceCode,
                                        'cityCode'     => $cityCode,
                                        'districtCode' => $districtCode,
                                    ]
                                );

                            $this->info(
                                vsprintf(
                                    "【id : %s】【省市区 : %s】 - 【省区code : %s】【市区code : %s】【地区code : %s】",
                                    [
                                        $v['id'],
                                        $v['addressPrefix'],
                                        $provinceCode,
                                        $cityCode,
                                        $districtCode,
                                    ]
                                )
                            );
                        }
                    }
                }
            }
            );

    }
}
